package com.sws.web.aspectj;

import com.sws.capture.domain.CaptureDto;
import com.sws.common.core.domain.AjaxResult;
import com.sws.common.core.domain.entity.SysUser;
import com.sws.common.utils.DateUtils;
import com.sws.customer.domain.RyCustomer;
import com.sws.customer.mapper.RyCustomerMapper;
import com.sws.push.domain.AIDto;
import com.sws.push.domain.RyMessagePush;
import com.sws.push.mapper.RyMessagePushMapper;
import com.sws.push.service.AIDialogue;
import com.sws.reservation.domain.RyReservation;
import com.sws.reservation.mapper.RyReservationMapper;
import com.sws.system.mapper.SysUserMapper;
import com.sws.wx_msg_push.dto.ReservationReminderDTO;
import com.sws.wx_msg_push.dto.ReservationTemplateDTO;
import com.sws.wx_msg_push.service.impl.ReservationReminderServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 人脸识别切面
 * 用于增强FaceCaptureController的faceCapture方法
 */
@Aspect
@Component
@Slf4j
public class FaceCaptureAspect {

    @Autowired
    private RyReservationMapper ryReservationMapper;

    @Autowired
    private RyMessagePushMapper ryMessagePushMapper;

    @Autowired
    private RyCustomerMapper ryCustomerMapper;

    @Autowired
    private  AIDialogue aiDialogue;

    @Autowired
    private  SysUserMapper sysUserMapper;

    @Autowired
    private ReservationReminderServiceImpl reservationReminderService;

    /**
     * 定义切点：FaceCaptureController的faceCapture方法
     */
    @Pointcut("execution(* com.sws.web.controller.student_attendance.capture.FaceCaptureController.faceCapture(..))")
    public void faceCapturePointcut() {
    }

    /**
     * 环绕通知：记录方法执行时间、参数和返回结果
     *
     * @param joinPoint 连接点
     */
    @Around("faceCapturePointcut()")
    public AjaxResult aroundFaceCapture(ProceedingJoinPoint joinPoint) throws Throwable {
        AjaxResult proceed = (AjaxResult) joinPoint.proceed();

        // 1.获取请求参数
        Object[] args = joinPoint.getArgs();
        CaptureDto captureDto;
        if (args.length > 0 && args[0] instanceof CaptureDto) {
            captureDto = (CaptureDto) args[0];
        } else {
            return null;
        }

        // 2.根据请求参数的Pid查询该客户的今天的预约信息
        String pid = captureDto.getPid();
        RyReservation ryReservation = new RyReservation();
        ryReservation.setCustomerPid(pid);
        ryReservation.setAppointmentTime(LocalDateTime.now());
        List<RyReservation> ryReservations = ryReservationMapper.selectRyReservationByAppointmentTimeAndCustomerPid(ryReservation);

        // 没有今天预约记录
        if (ryReservations.isEmpty()) {
            return null;
        }

        // 3.查询全部的前台人员
        List<SysUser> sysUsers = sysUserMapper.selectUserByNickName("前台");
        if (sysUsers.isEmpty()) {
            return null;
        }

        sysUsers.forEach(querySysUser -> {
            // 4.有今天预约记录，调用新增消息推送的方法,推送给全部的前台人员,和推送给微信
            ryReservations.forEach(queryRyReservation -> {
                // 5.给消息推送记录插入数据
                RyMessagePush ryMessagePush = new RyMessagePush();
                ryMessagePush.setSendTime(DateUtils.getNowDate());
                ryMessagePush.setEndTime(DateUtils.toDate(LocalDate.now().plusDays(1)));

                // 根据pid查询客户id和名字,逻辑上只有一条数据返回
                RyCustomer ryCustomer = new RyCustomer();
                ryCustomer.setPid(queryRyReservation.getCustomerPid());
                List<RyCustomer> ryCustomers = ryCustomerMapper.selectRyCustomerList(ryCustomer);
                if (ryCustomers.isEmpty()) {
                    return;
                }
                RyCustomer queryRyCustomer = ryCustomers.get(0);
                ryMessagePush.setCustomerId(queryRyCustomer.getId());
                ryMessagePush.setCustomerName(queryRyCustomer.getName());

                // AI生成消息推送内容
                String message = "请帮我分析这个客户最近的消费习惯和消费偏好，还有它需要什么服务，和产品";
                Long id = queryRyCustomer.getId();
                AIDto aiDto = new AIDto();
                aiDto.setContent(message);
                aiDto.setCustomerId(id);
                Flux<String> stringFlux = aiDialogue.AIchat(aiDto);
                String content = String.join("", Objects.requireNonNull(stringFlux.collectList().block()));
                ryMessagePush.setContent(content);

                ryMessagePush.setIsConfirmed(0);
                ryMessagePush.setUrgencyLevel(1);
                ryMessagePush.setContactPerson(querySysUser.getPhonenumber());
                ryMessagePush.setPushName(querySysUser.getNickName());
                ryMessagePush.setPushId("user_" + querySysUser.getUserId());
                ryMessagePush.setPushType("user");
                ryMessagePush.setCreateTime(DateUtils.getNowDate());

                // 6.插入数据库
                ryMessagePushMapper.insertRyMessagePush(ryMessagePush);

                // 7.推送给微信
                ReservationReminderDTO reservationReminderDTO = new ReservationReminderDTO();
                reservationReminderDTO.setOpenid(queryRyCustomer.getOpenid());
                reservationReminderDTO.setAppointmentTime(queryRyReservation.getAppointmentTime());
                reservationReminderDTO.setStaffName(queryRyReservation.getStaffName());
                reservationReminderDTO.setServiceContent(queryRyReservation.getServiceContent());
                reservationReminderDTO.setRoomNo(queryRyReservation.getRoomNo());
                reservationReminderDTO.setCustomerName(queryRyCustomer.getName());
                reservationReminderService.sendArriveReservationReminder(reservationReminderDTO);
            });
        });
        return proceed;
    }
}
